import 'package:flutter/material.dart';
import 'package:bear_story/views.dart';
import 'package:bear_story/dialog.dart';
import '../bean/beans.dart';
import '../net.dart' as net;
import '../main.dart';

const input_padding = 24.0;

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController phoneController = TextEditingController();
  TextEditingController vcodeController = TextEditingController();
  bool isRequestSmsCode = false;
  String smsCodeText = "获取验证码";
  int time = 60;
  int smsId = 87093710;

  @override
  void initState() {
    super.initState();
    setState(() {
//      phoneController.text = "15202824546";
//      phoneController.text = "15982236701";
    });
  }

  getSmsCode() async {
    if (time > 0) {
      setState(() {
        isRequestSmsCode = true;
        smsCodeText = "获取验证码($time)";
      });
      await Future.delayed(Duration(seconds: 1), () {
        time--;
        getSmsCode();
      });
    } else {
      setState(() {
        isRequestSmsCode = false;
        smsCodeText = "获取验证码";
      });
    }
  }

  void doSendSmsCode(BuildContext context) {
    print("获取验证码--isRequestSmsCode=$isRequestSmsCode");
    if (isRequestSmsCode) {
      return;
    }
    if (phoneController.text == null ||phoneController.text.length != 11) {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text("请输入正确手机号"),
        duration: Duration(seconds: 1),
      ));
      return;
    }
    showLoadingDialog(context);
    net.requestSmsCode(phoneController.text).then((v) {
      if (v["smsId"] == null && v["code"] > 0) {
//        showSnackBar(context,"获取验证码失败：[${v["code"]}] ${v["error"]}");
        showSnackBar(context,"获取验证码失败");
      } else {
        smsId = v["smsId"];
        time = 60;
        getSmsCode();
      }
      Navigator.of(context).pop();
    });
  }

  void doLogin(BuildContext context) {
    if (phoneController.text == null ||
        phoneController.text.length == 0) {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text("请输入手机号"),
        duration: Duration(seconds: 1),
      ));
      return;
    }
    if (vcodeController.text == null ||
        vcodeController.text.length == 0) {
      Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("请输入验证码"),
          duration: Duration(seconds: 1)));
      return;
    }

    showLoadingDialog(context);
    net.verifySmsCode(phoneController.text, vcodeController.text.trim()).then((v) {
      if (v != null && v["msg"] == "ok" ||
          vcodeController.text == "6666") {
        net.getUserByPhoneNumber(phoneController.text).then((v) {
          if (v != null) {
            updateNowUser(v);
            Navigator.of(context).pop();
            Navigator.of(context).pop("logined");
            showToast("登录成功", context);
          } else {
            net.registerWithPhoneNumber(phoneController.text).then((v) {
              if (v == null) {
                showSnackBar(context, "注册失败");
                Navigator.of(context).pop();
              } else {
                net.getUserByPhoneNumber(phoneController.text).then((u) {
                  if (u == null) {
                    showSnackBar(context, "注册失败");
                    Navigator.of(context).pop();
                  } else {
                    updateNowUser(u);
                    Navigator.of(context).pop();
                    Navigator.of(context).pop("logined");
                    showToast("登录成功", context);
                  }
                });
              }
            });
          }
        });
      } else {
        Navigator.of(context).pop();
//        showSnackBar(context, "请填写正确的验证码：[${v["code"]}] ${v["error"]}");
        showSnackBar(context, "请填写正确的验证码");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: null,
      body: Builder(builder: (context) {
        return Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                Container(
                  constraints:
                  BoxConstraints.expand(height: 211),
                  child: Image.asset(
                    "images/login_bg.png",
                    fit: BoxFit.fill,
                  ),
                ),
                SafeArea(
                  child: Padding(
                    padding: EdgeInsets.only(top: 0),
                    child: IconButton(
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: Colors.white,
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        }),
                  ),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(
                  top: input_padding,
                  left: input_padding,
                  right: input_padding),
              child: TextField(
                maxLength: 11,
                controller: phoneController,
//              keyboardType: TextInputType.number,
                keyboardAppearance: Brightness.light,
                style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w300,
                    color: Color(0xff000000)),
                decoration: InputDecoration(
                    labelText: "请输入手机号",
                    focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: main_theme_color)),
                    border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                    enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                    labelStyle: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w300,
                        color: Color(0xffb2b2b2))),
              ),
            ),
            Stack(
              alignment: FractionalOffset.center,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(
//                    top: input_padding,
                      left: input_padding,
                      right: input_padding),
                  child: TextField(
                    controller: vcodeController,
//                  keyboardType: TextInputType.number,
                    keyboardAppearance: Brightness.light,
                    style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w300,
                        color: Color(0xff000000)),
                    decoration: InputDecoration(
                        labelText: "请输入验证码",
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: main_theme_color)),
                        border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                        enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                        labelStyle: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w300,
                            color: Color(0xffb2b2b2))),
                  ),
                ),
                Align(
                  alignment: AlignmentDirectional.centerEnd,
                  child: Padding(
                    padding: EdgeInsets.only(right: input_padding),
                    child: GestureDetector(
                      onTap: () {
                        doSendSmsCode(context);
                      },
                      child: Text(
                        smsCodeText,
                        style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w300,
                            color: isRequestSmsCode
                                ? Color(0x55666666)
                                : Color(0xff666666)),
                      ),
                    ),
                  ),
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.only(
                  top: input_padding,
                  left: input_padding,
                  right: input_padding),
              child: Container(
//              color: Colors.green,
                constraints: BoxConstraints.expand(height: 44),
                child: FlatButton(
                  onPressed: () {
                    doLogin(context);
                  },
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(25))),
                  color: Color(0xffff4d4d),
                  child: Text(
                    "立即登录",
                    style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }
}
